package com.khh.controller;

import com.khh.entity.User;
import com.khh.helper.MybatisHelp;
import com.khh.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by webrx on 2017-09-05.
 */

@Controller
public class UserController {

    MybatisHelp mh = new MybatisHelp();
    SqlSession ss = mh.getSs();
    UserMapper bdao = ss.getMapper(UserMapper.class);

    @RequestMapping("/query")
    public String query(Model model){
        model.addAttribute("userall", bdao.queryAllByZhu());
        return "user/user";
    }

    @RequestMapping("/delete/{id}")
    public String del(@PathVariable("id") int id){
        int n = bdao.deleteByPrimaryKey(id);
        ss.commit();
        return "redirect: /query";
    }

    @RequestMapping("/updateSelect/{id}")
    public String ins(@PathVariable("id") int id,Model model){
        model.addAttribute("querybyid",bdao.queryByIdLazy(id));
        return "user/update";
    }

    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    public String update(HttpServletRequest req){
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        User user = new User();
        user.setUid(Integer.parseInt(id));
        user.setUname(name);
        user.setUage(Integer.parseInt(age));
        int n = bdao.updateByPrimaryKey(user);
        ss.commit();
        return "redirect: /query";
    }

    @RequestMapping(value = "/insturn")
    public String inserts(){
        return "/user/add";
    }

    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insert(HttpServletRequest req){
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        User user = new User();
        user.setUname(name);
        user.setUage(Integer.parseInt(age));
        int n = bdao.insert(user);
        ss.commit();
        return "redirect: /query";
    }

    @RequestMapping(value = "/insertByuser",method = RequestMethod.POST)
    public String insertByUser(User user){
        int n = bdao.insertByUser(user);
        ss.commit();
        return "redirect: /query";
    }
}
